<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">

    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（标题和用户名字段可查）"
                style="width: 21%"
                clearable></el-input>
      <el-button style="margin-left: 10px" type="primary" @click="add">新增</el-button>
      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" sortable fixed prop="knowledgeId" width="80" label="知识ID"/>
      <el-table-column sortable prop="title" width="250" label="灌输标题"/>
      <el-table-column sortable prop="content" width="280" label="灌输内容"/>
      <el-table-column sortable prop="username" width="180" label="知识灌输者"/>
      <el-table-column sortable prop="createTime" min-width="230" label="灌输时间"/>

      <el-table-column sortable prop="isDeleted" width="180" label="状态">
        <template #default="scope">
          <span>
            {{
              scope.row.isDeleted ? '已禁用' : '应用中'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" :icon="Edit">
            编辑
          </el-button>
          <el-popconfirm title="确定永久删除吗?" v-model="scope.visible" @confirm="deleteForever(scope.row.knowledgeId)">
            <template v-slot:reference>
              <el-button type="primary" link :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>

    <el-dialog v-model="data.centerDialogVisible" title="请输入更新的知识灌输信息" width="30%" center style="margin-top: 150px">
      <el-form :model="data.form" label-width="60px">
        <el-form-item style="margin-left: 50px" label="标 题">
          <el-input v-model="data.form.title" style="width: 80%;" placeholder="请输入灌输标题"/>
        </el-form-item>

        <el-form-item style="margin-left: 50px" label="内 容">
          <el-input type="textarea" v-model="data.form.content" :rows="5" style="width: 80%;"
                    placeholder="请输入灌输内容"/>
        </el-form-item>
        <el-form-item style="margin-left: 50px" label="状 态">
          <div class="mb-2 flex items-center text-sm" style="margin-left: 30px">
            <el-radio-group v-model="data.form.isDeleted" class="ml-4">
              <el-radio :label="1">禁 用</el-radio>
              <el-radio :label="0">应 用</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="save">确认</el-button>
            </span>
      </template>
    </el-dialog>

    <el-dialog v-model="data.addDialogVisible" title="请输入新增的知识灌输信息" width="30%" center>
      <el-form :model="data.addForm" label-width="60px">
        <el-form-item style="margin-left: 50px" label="标 题">
          <el-input v-model="data.addForm.title" style="width: 80%;" placeholder="请输入灌输标题"/>
        </el-form-item>

        <el-form-item style="margin-left: 50px" label="内 容">
          <el-input type="textarea" v-model="data.addForm.content" :rows="5" style="width: 80%;"
                    placeholder="请输入灌输内容"/>
        </el-form-item>
        <el-form-item style="margin-left: 50px" label="状 态">
          <div class="mb-2 flex items-center text-sm" style="margin-left: 30px">
            <el-radio-group v-model="data.addForm.isDeleted" class="ml-4">
              <el-radio :label="1">禁 用</el-radio>
              <el-radio :label="0">应 用</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.addDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addSave">确认</el-button>
            </span>
      </template>
    </el-dialog>

  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {reactive} from "vue";
import {Delete, Edit} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {useRouter} from "vue-router";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';

const dataString = localStorage.getItem('data');
const userLoginData = dataString ? JSON.parse(dataString) : null;


const data = reactive({
  //弹窗默认关闭
  centerDialogVisible: false,
  addDialogVisible: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 5,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  //编辑表单
  form: {},
  selectedRows: [],
  addForm: {
    title: null,
    content: null,
    userId: userLoginData.userId,
    isDeleted: 0,
  }
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/knowledge/all?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("助手管理数据：", response);
        data.tableData = response.data;
        data.total = response.data.length;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}


const router = useRouter();

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//让form对象独立出来，还能包含那一行的数据
  data.centerDialogVisible = true;
}


const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

const deleteForever = (knowledgeId) => {
  const selectedRows = [];
  selectedRows.push(knowledgeId);
  request.delete(`/java/knowledge/delete/${selectedRows}`).then((res) => {
    Load()
  })
}

const handleBatchDelete = async () => {
  const selectedRows = data.selectedRows.map((row) => row.knowledgeId);
  if (selectedRows.length === 0) {
    ElMessage.error('没有选中任何行');
    return;
  }

  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定永久删除选中的行吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    request.delete(`/java/knowledge/delete/${selectedRows}`).then((res) => {

      Load()
    })
  }
}

const save = async () => {
  data.centerDialogVisible = false;

  const editData = {
    knowledgeId: data.form.knowledgeId,
    title: data.form.title,
    content: data.form.content,
    userId: userLoginData.userId,
    isDeleted: data.form.isDeleted ? 1 : 0
  }

  console.log("编辑信息功能——前端传递的数据:", editData);

  // 使用await等待PUT请求完成
  try {
    const response = await request.put(`/java/knowledge/edit`, editData);
    if (response.code === 200) {
      ElMessage.info("保存成功")
    } else {
      ElMessage.error("保存失败")
    }
  } catch (error) {
    ElMessage.error(error.message)
  }

  // 然后调用Load函数
  Load();
}

const add = () => {
  data.addDialogVisible = true;
  data.addForm.title = "";
  data.addForm.content = "";
}


const addSave = () => {
  data.addDialogVisible = false
  request.post(`/java/knowledge/push`, data.addForm).then((res) => {
    if (res.code === 200) {
      ElMessage.info("新增成功")
    } else {
      ElMessage.error("新增失败")
    }
    Load();
  })
}
</script>
